<!-- 正文开始 -->
<div class="layui-fluid">
    <div class="layui-card">
        <div class="layui-card-body">
            <!-- 头部操作栏 -->
            <form class="layui-form lay-header">
                <div class="toolbar">
                    <div class="layui-form-item lay-query-content">
                        <div class="lay-query-box">
                            <div class="query-lt">
                                <div class="layui-inline">
                                    <label class="layui-form-label w-auto">订单编号：</label>
                                    <div class="layui-input-inline">
                                        <input type="text" class="layui-input" placeholder="请输入订单编号" name="name">
                                    </div>
                                </div>
                            </div>
                            <div class="query-rt">
                                <div class="layui-inline">
                                    <a class="layui-btn icon-btn" lay-filter="formSubSearchLog" lay-submit layui-form-keyDownSearch="true">查询</a>
                                    <button class="layui-btn icon-btn color-white" lay-filter="searchReset" lay-submit type="reset">重置</button>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
                <div class="lay-btn-rows">
                    <div class="lay-btn-box">
                        <div class="lay-btn-lt">
                            <a id="deviceModelDle" class="layui-btn layui-btn-danger">批量删除</a>
                            <a id="deviceModelBtnAdd" class="layui-btn color-reseda">添加</a>
                        </div>
                        <div class="lay-btn-rt">
                        </div>
                    </div>
                </div>
            </form>
            <!-- 表格 -->
            <table class="layui-table" id="deviceModelTable" lay-filter="deviceModelTable"></table>
        </div>
    </div>
</div>

<style>
    .red{
        color: red;
    }
    .deviceModelForm label{
        width: 120px;
    }
    .borderNone{
        border: none;
    }
    .companyFormPhotos{
        /* margin-left:140px; */
        line-height: 38px;
        float: left;
        margin-right: 30px;
    }
    .companyFormPhotos img{
        cursor: pointer;
        height: 38px;
        width: auto;
        max-width: 200px;
    }
</style>
<!-- 表格操作列 -->
<script type="text/html" id="deviceModelTableBar">
    <a class="layui-btn layui-btn-primary layui-btn-xs" lay-event="details">详情</a>
    <a class="layui-btn layui-btn-primary layui-btn-xs" lay-event="edit">修改</a>
    <a class="layui-btn layui-btn-danger layui-btn-xs" lay-event="del">删除</a>
</script>

<!-- 表单弹窗 -->
<script type="text/html" id="deviceModelForm">
    <form lay-filter="deviceModelForm" class="layui-form model-form deviceModelForm">
        <input name="id" type="hidden"/>
        <div class="layui-form-item">
            <label class="layui-form-label"><span class="red">*</span>设备类型</label>
            <div class="layui-input-inline">
                <select name="deviceType" lay-filter="deviceModel" lay-verify="required" required id="deviceModel"></select>
            </div>
        </div>
        <div class="layui-form-item">
            <label class="layui-form-label"><span class="red">*</span>设备品牌</label>
            <div class="layui-input-inline">
                <select name="deviceBrand" lay-filter="deviceBrand" lay-verify="required" required id="deviceBrand"></select>
            </div>
        </div>
        <div class="layui-form-item">
            <label class="layui-form-label"><span class="red">*</span>设备型号名称</label>
            <div class="layui-input-inline">
                <input name="name" placeholder="请输入设备型号" type="text" class="layui-input" lay-verify="required"/>
            </div>
        </div>
        <div class="layui-form-item">
            <label class="layui-form-label"><span class="red">*</span>设备型号编码</label>
            <div class="layui-input-inline">
                <input name="modelNo" placeholder="请输入设备型号" type="text" class="layui-input" lay-verify="required"/>
            </div>
        </div>
        <div class="layui-form-item">
            <label class="layui-form-label"><span class="red">*</span>设备编码头</label>
            <div class="layui-input-inline">
                <input name="deviceHead" placeholder="请输入设备编码头" type="text" class="layui-input" lay-verify="required"/>
            </div>
        </div>
        <div class="layui-form-item">
            <label class="layui-form-label">设备照片</label>
            <div class="layui-input-block">
                <div id="btnUploadCredentials_path" class="companyFormPhotos"></div>
                <div id="btnUploadCredentials" class="layui-btn" style="float: left;"><i class="layui-icon">&#xe681;</i>上传图片</div>
                <input name="devicePic" type="hidden" class="layui-input" lay-verify="" id="devicePic"/>
            </div>
        </div>
        <div class="layui-form-item">
            <label class="layui-form-label">夹具数量</label>
            <div class="layui-input-inline">
                <input name="fixtureAmount"  type="number" class="layui-input" lay-verify="required" />
            </div>
        </div>
        <!--        <div class="layui-form-item">-->
        <!--            <label class="layui-form-label"><span class="red">*</span>供应商</label>-->
        <!--            <div class="layui-input-inline">-->
        <!--                <select name="supplier" lay-filter="supplier" lay-verify="required" required id="supplier"></select>-->
        <!--            </div>-->
        <!--        </div>-->
        <!--        <div class="layui-form-item">-->
        <!--            <label class="layui-form-label">供应商联系人</label>-->
        <!--            <div class="layui-input-inline">-->
        <!--                <input name="supplierLink"  type="text" class="layui-input" lay-verify="required" />-->
        <!--            </div>-->
        <!--        </div>-->
        <div class="layui-form-item">
            <label class="layui-form-label">厂家名称</label>
            <div class="layui-input-inline">
                <div class="layui-input-inline">
<!--                    <select name="factoryId" lay-filter="factoryId" lay-verify="required" required id="factoryId"></select>-->
                    <input name="factoryName" id="factoryName"  type="text" class="layui-input" required/>
                </div>
            </div>
<!--            <button type="button" class="layui-btn" id="factoryIdAdd">点击添加</button>-->
        </div>
        <!-- <label class="layui-form-label">厂家联系人</label>-->
<!--        <input name="factoryName" id="factoryName"  type="hidden" class="layui-input"/>-->

        <div class="layui-form-item">
            <label class="layui-form-label">厂家联系人</label>
            <div class="layui-input-inline">
                <input name="factoryContact" id="factoryContact"  type="text" class="layui-input" />
            </div>
        </div>
        <div class="layui-form-item">
            <label class="layui-form-label">厂家网站</label>
            <div class="layui-input-inline">
                <input name="factoryUrl"  id="factoryUrl" type="text" class="layui-input"  />
            </div>
        </div>
        <div class="layui-form-item">
            <label class="layui-form-label">设备资料</label>
            <div class="layui-input-block">
                <div id="btnUploadDviceAppendix_path" class="companyFormPhotos"></div>
                <div id="btnUploadDviceAppendix" class="layui-btn" style="float: left;"><i class="layui-icon">&#xe681;</i>上传</div>
                <input name="deviceAppendix" type="hidden" class="layui-input" lay-verify="" id="deviceAppendix"/>
            </div>
        </div>
        <div class="layui-form-item">
            <label class="layui-form-label"><span class="red">*</span>备注说明</label>
            <div class="layui-input-inline">
                <input name="remark" type="text" class="layui-input" lay-verify="required" />
            </div>
        </div>
        <div class="layui-form-item">
            <label class="layui-form-label"></label>
            <div class="layui-input-inline">
                <button class="layui-btn" lay-filter="deviceModelFormSubmit" lay-submit id="deviceModelFormSubmit">提交</button>
            </div>
        </div>
    </form>
</script>

<script type="text/html" id="searchManufactureForm">
    <form lay-filter="searchManufactureForm" class="layui-form model-form" style="padding:20px">
        <div class="layui-input-inline">
            <div class="layui-input-inline">
                <input type="text" class="layui-input" id="searchManufactureIpt">
            </div>
            <button type="button" class="layui-btn" id="searchManufactureBtn"><i class="layui-icon">&#xe615;</i></button>
        </div>
    </form>
</script>

<!-- js部分 -->
<script>
    layui.use(['layer', 'form', 'table', 'admin','upload'], function () {
        var $ = layui.jquery;
        var layer = layui.layer;
        var form = layui.form;
        var table = layui.table;
        var config = layui.config;
        var admin = layui.admin;
        var upload = layui.upload;

        //厂家信息 "name":"湖南云端商业管理有限公司"
        let facFactoryData = []
        admin.req('enterprise/factory/admin/facFactory/list', {}, function (res) {
            if (res.code == 200) {
                facFactoryData = res.data
            }
        }, 'GET');

        // 渲染表格
        var insTb = table.render({
            elem: '#deviceModelTable',
            url: config.base + 'enterprise/device/admin/deviceModel/list',
            page: true,
            cellMinWidth: 100,
            cols: [[
                {type: 'checkbox'}
                // ,{field: 'id', sort: true, title: 'ID'}
                ,{type: 'numbers', title: '序号'}
                ,{field: 'modelNo', sort: true, title: '设备型号编码'}
                ,{field: 'deviceBrand', sort: true, title: '所属品牌'}
                ,{field: 'deviceType', sort: true, title: '设备类型'}
                ,{field: 'factoryName', sort: true, title: '所属厂家'}
                ,{field: 'remark', sort: true, title: '备注描述'}
                ,{field: 'fixtureAmount', sort: true, title: '数量'}
                ,{field: 'unit', sort: true, title: '单位'}
                ,{field: 'createTime', sort: true, title: '添加时间'}
                ,{align: 'center', toolbar: '#deviceModelTableBar', title: '操作',width:175}
            ]]
        });

        var flag=true;
        // 工具条点击事件
        table.on('tool(deviceModelTable)', function (obj) {
            var data = obj.data;
            if (obj.event === 'details') { //详情
                flag=true;
                showEditModel(data);
            } else if (obj.event === 'del') { // 删除
                doDelete(obj);
            } else if(obj.event === 'edit'){//修改
                flag=false;
                showEditModel(data);
            }
        });

        //监听排序
        table.on('sort(deviceModelTable)', function(obj){
            table.reload('deviceModelTable', {
                initSort: obj
                ,where: {
                    sort: obj.field
                    ,order: obj.type
                }
            });
        });

        // 搜索
        form.on('submit(formSubSearchLog)', function (data) {
            insTb.reload({where: data.field,page: {curr: 1}},'data');
        });

        // 添加按钮点击事件
        $('#deviceModelBtnAdd').click(function () {
            showEditModel();
        });





        // 显示编辑弹窗
        function showEditModel(data) {
            admin.open({
                type: 1,
                area: '840px',
                offset: '65px',
                title: data ? (flag?'设备型号详情':'修改设备型号') : '添加设备型号',
                content: $('#deviceModelForm').html(),
                success: function () {
                    // if(facFactoryData.length>0){
                    //     loadSelectHtml(facFactoryData, "请选择厂家", "factoryId",1)
                    // }
                    if(data&&flag){
                        facFactoryData.forEach(item=>{
                            if(data.factoryId == item.id){
                                // data.factoryName = item.factoryName;
                                data.factoryContact = item.factoryContact;
                                data.factoryAddress = item.factoryAddress;
                                data.factoryPhone = item.factoryPhone;
                                data.factoryUrl = item.factoryUrl;
                                // data.factoryName = item.factoryName;
                            }
                        })

                        form.val('deviceModelForm', data);
                        $("#btnUploadCredentials_path").html("<img src='"+data.devicePic+"'/>")
                        $("#btnUploadDviceAppendix_path").html("<img src='"+data.deviceAppendix+"'/>")

                        $.each($('.deviceModelForm input'),(index,value)=>{
                            $(value).attr("disabled",'')
                        });
                        $.each($('.deviceModelForm select'),(index,value)=>{
                            $(value).attr("disabled",'')
                        });

                        $('#deviceModel').html('<option value="">'+data.deviceType+'</option>')
                        $('#deviceBrand').html('<option value="">'+data.deviceBrand+'</option>')
                        $('#supplier').html('<option value="">'+data.supplier+'</option>')
                        $('#deviceModelFormSubmit').css("display","none")
                        $('#btnUploadCredentials').css("display","none")
                        $('#btnUploadDviceAppendix').css("display","none")
                        $('#factoryIdAdd').hide()

                    }else if(data&&!flag){
                        facFactoryData.forEach(item=>{
                            if(data.factoryId == item.id){
                                data.factoryContact = item.factoryContact;
                                data.factoryAddress = item.factoryAddress;
                                data.factoryPhone = item.factoryPhone;
                                data.factoryUrl = item.factoryUrl;
                            }
                        })

                        $("#btnUploadCredentials_path").html("<img src='"+data.devicePic+"'/>")
                        $("#btnUploadDviceAppendix_path").html("<img src='"+data.deviceAppendix+"'/>")
                        //设备类型
                        admin.reqSync('enterprise/device/admin/deviceType/list?page=1&limit=9999', {}, function (res) {
                            layer.closeAll('loading');
                            if (res.code == 200) {
                                loadSelectHtml(res.data, "请选择设备类型", "deviceType")
                            }
                        }, 'GET');
                        $('#factoryIdAdd').click(function () {
                            showSearchManufactureForm()
                        })
                        //设备品牌
                        admin.reqSync('enterprise/device/admin/deviceBrand/list?page=1&limit=9999', {}, function (res) {
                            layer.closeAll('loading');
                            if (res.code == 200) {
                                loadSelectHtml(res.data, "请选择设备品牌", "deviceBrand")
                            }
                        }, 'GET');

                        //供应商supplier
                        admin.req('enterprisecab/cabinet/app/supplier/list?page=1&limit=9999', {}, function (res) {
                            layer.closeAll('loading');
                            if (res.code == 200) {
                                loadSelectHtml(res.data, "请选择供应商", "supplier",5)
                            }
                        }, 'GET');
                        form.val('deviceModelForm', data);
                        $('#btnUploadCredentials').click(uploadImg('btnUploadCredentials','btnUploadCredentials_path','devicePic'))
                        $('#btnUploadDviceAppendix').click(uploadImg('btnUploadDviceAppendix','btnUploadDviceAppendix_path','deviceAppendix'))
                    }else {
                        //设备类型
                        admin.req('enterprise/device/admin/deviceType/list?page=1&limit=9999', {}, function (res) {
                            layer.closeAll('loading');
                            if (res.code == 200) {
                                loadSelectHtml(res.data, "请选择设备类型", "deviceType")
                            }
                        }, 'GET');

                        // form.on("select(factoryId)", function (data) {
                        //     facFactoryData.forEach((item,index)=>{
                        //         if(data.value == item.id){
                        //             $("#factoryUrl").val(item.factoryUrl)
                        //             $("#factoryContact").val(item.factoryContact);
                        //             $("#factoryName").val(item.factoryName)
                        //         }
                        //     })
                        // })
                        $('#factoryIdAdd').click(function () {
                            showSearchManufactureForm()
                        })


                        //设备品牌
                        admin.req('enterprise/device/admin/deviceBrand/list?page=1&limit=9999', {}, function (res) {
                            layer.closeAll('loading');
                            if (res.code == 200) {
                                loadSelectHtml(res.data, "请选择设备品牌", "deviceBrand")
                            }
                        }, 'GET');

                        //供应商supplier
                        admin.req('enterprisecab/cabinet/app/supplier/list?page=1&limit=9999', {}, function (res) {
                            layer.closeAll('loading');
                            if (res.code == 200) {
                                loadSelectHtml(res.data, "请选择供应商", "supplier",5)
                            }
                        }, 'GET');
                        $('#btnUploadCredentials').click(uploadImg('btnUploadCredentials','btnUploadCredentials_path','devicePic'))
                        $('#btnUploadDviceAppendix').click(uploadImg('btnUploadDviceAppendix','btnUploadDviceAppendix_path','deviceAppendix'))

                    }
                    // 渲染下拉框
                    form.render('select');

                    // 查看大图
                    layer.photos({
                        photos: '.companyFormPhotos'
                        ,anim: 5
                    });
                    // 表单提交事件
                    form.on('submit(deviceModelFormSubmit)', function (d) {
                        layer.load(2);
                        admin.req(data ? 'enterprise/device/admin/deviceModel/update' : 'enterprise/device/admin/deviceModel/add', d.field, function (res) {
                            layer.closeAll('loading');
                            if (res.code == 200) {
                                layer.msg(res.msg, {icon: 1});
                                table.reload('deviceModelTable');
                                layer.closeAll('page');
                            } else {
                                layer.msg(res.msg, {icon: 2});
                            }
                        }, data ? 'PUT' : 'POST');
                        return false;
                    });
                }
            });
        }


        //搜索添加厂家
        function showSearchManufactureForm() {
            admin.open({
                type: 1,
                area: ['400px',"500px"],
                offset: '100px',
                title: "添加",
                content: $('#searchManufactureForm').html(),
                success: function () {
                    $("#searchManufactureBtn").click(()=>{
                        if ($("#searchManufactureIpt").val()){
                            admin.req('enterprise/factory/admin/facFactory/list', {name:$("#searchManufactureIpt").val()}, function (res) {
                                console.log(res)
                            }, 'GET');
                        }else {
                            layer.msg('请输入厂家名称', {icon: 2});
                        }
                    })
                }
            })
        }

        // 上传图片
        function uploadImg(_elem, pathId, inputId) {
            upload.render({
                elem: '#' + _elem
                , url: config.upload_url + 'uploadFile'
                , data: {}
                , accept: 'file'
                , exts: 'jpg|png|RAR|zip|pdf|txt|doc|docx|xls|xlsx|ppt|pptx'
                , headers: { Authorization: 'Bearer ' + config.getToken() }
                , done: function (res) {
                    if (res.code == 200) {
                        layer.msg(res.msg || "上传成功", { icon: 1 });
                        let imagUrl = res.data.url;
                        $('#' + pathId).html('<img src="' +imagUrl + '"/>');
                        $('#' + inputId).val(imagUrl);
                    } else if (res.code == 502) {
                        return location.replace('admin/login.html');
                    } else {
                        layer.msg(res.msg || "上传失败", { icon: 2 });
                    }
                }
            });
        }


        // 删除
        function doDelete(obj) {
            let url='';
            if(typeof obj == 'string'){
                url = 'enterprise/device/admin/deviceModel/delBatch?ids='+obj
            }else {
                url = 'enterprise/device/admin/deviceModel/'+obj.data.id
            }
            layer.confirm('确定要删除吗？', {
                offset: '65px',
                skin: 'layui-layer-admin'
            }, function (i) {
                layer.close(i);
                layer.load(2);
                admin.req(url, {}, function (res) {
                    layer.closeAll('loading');
                    if (res.code == 200) {
                        layer.msg(res.msg, {icon: 1});
                        table.reload('deviceModelTable');
                        // obj.del();
                    } else {
                        layer.msg(res.msg, {icon: 2});
                    }
                }, 'DELETE');
            });
        }

        // 导出excel
        $('#deviceModelDle').click(function () {
            var checkRows = table.checkStatus('deviceModelTable');
            if (checkRows.data.length == 0) {
                layer.msg('请选择要批量的数据', {icon: 2});
            } else {
                let ids = []
                checkRows.data.forEach((item,index)=>{
                    ids.push(item.id)
                })
                doDelete(ids.join())
            }
        });

        // option渲染
        function loadSelectHtml(data, tips, htmltarget, type) {
            let html = ' <option value>' + tips + '</option>';
            if (!data || data == null) {
                return;
            }
            for (let i = 0; i < data.length; i++) {
                if (type == 1) {
                    html += `<option value='${data[i].id}' id='${data[i].factoryName}'>${data[i].factoryName}</option>`;
                } else if (type == 2) {
                    html += `<option value='${data[i].skuCode}'>${data[i].skuCode}</option>`;
                } else if (type == 3) {
                    html += `<option value='${data[i].id}'>${data[i].warehouseName}</option>`;
                }else if(type == 4){
                    html += `<option value='${data[i].skuCode}'  skuCode='${data[i].skuCode}'>${data[i].skuName}</option>`;
                } else if(type == 5){
                    html += `<option value='${data[i].companyName}'>${data[i].companyName}</option>`;
                } else {
                    html += `<option value='${data[i].name}'>${data[i].name}</option>`;
                }
            }

            $("form select[name='" + htmltarget + "']").html(html);
            form.render('select');
        }

    });
</script>